package com.nidu.demo.log.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.log.convertor.OperateLogConvertor;
import com.nidu.demo.log.gateway.OperateLogGateway;
import com.nidu.demo.log.mapper.OperateLogMapper;
import com.nidu.demo.log.mapper.dataobject.OperateLogDO;
import com.nidu.demo.log.model.OperateLog;
import com.nidu.demo.log.model.OperateLogCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 操作日志网关实现
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class OperateLogGatewayImpl implements OperateLogGateway {

    private final OperateLogMapper mapper;
    private final OperateLogConvertor convertor;

    @Override
    public OperateLog create(OperateLog operateLog) {
        OperateLogDO operateLogDO = convertor.toDataObject(operateLog);
        mapper.insert(operateLogDO);
        return convertor.toDomainObject(operateLogDO);
    }

    @Override
    public OperateLog update(OperateLog operateLog) {
        OperateLogDO operateLogDO = convertor.toDataObject(operateLog);
        mapper.updateById(operateLogDO);
        return convertor.toDomainObject(operateLogDO);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    public OperateLog getById(Long id) {
        OperateLogDO operateLogDO = mapper.selectById(id);
        if (operateLogDO == null) {
            return null;
        }
        return convertor.toDomainObject(operateLogDO);
    }

    @Override
    public List<OperateLog> getByIds(Set<Long> ids) {
        LambdaQueryWrapper<OperateLogDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OperateLogDO::getId, ids);
        List<OperateLogDO> operateLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(operateLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(operateLogDOS);
    }

    @Override
    public List<OperateLog> listByCondition(OperateLogCriteria criteria) {
        LambdaQueryWrapper<OperateLogDO> wrapper = buildQueryWrapper(criteria);
        List<OperateLogDO> operateLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(operateLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(operateLogDOS);
    }

    @Override
    public PageResponse<OperateLog> pageByCondition(OperateLogCriteria criteria) {
        // 创建查询条件
        LambdaQueryWrapper<OperateLogDO> wrapper = buildQueryWrapper(criteria);

        // 创建分页对象
        Page<OperateLogDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }

        // 执行分页查询
        mapper.selectPage(page, wrapper);
        List<OperateLog> operateLogs = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(operateLogs, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public void deleteAll() {
        mapper.deleteAll();
    }

    private LambdaQueryWrapper<OperateLogDO> buildQueryWrapper(OperateLogCriteria criteria) {
        LambdaQueryWrapper<OperateLogDO> wrapper = new LambdaQueryWrapper<>();
        
        // 时间范围条件
        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(OperateLogDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(OperateLogDO::getCreateTime, createTime[0], createTime[1]);
            }
        }
        
        // 操作时间范围条件（使用createTime作为操作时间）
        LocalDateTime[] startTime = criteria.getStartTime();
        if (startTime != null) {
            if (startTime.length == 1 && startTime[0] != null) {
                wrapper.ge(OperateLogDO::getCreateTime, startTime[0]);
            } else if (startTime.length > 1 && startTime[0] != null && startTime[1] != null) {
                wrapper.between(OperateLogDO::getCreateTime, startTime[0], startTime[1]);
            }
        }
        
        // 精确查询条件
        wrapper.eq(criteria.getUserId() != null, OperateLogDO::getUserId, criteria.getUserId());
        wrapper.eq(criteria.getType() != null, OperateLogDO::getType, criteria.getType());
        wrapper.eq(criteria.getSubType() != null, OperateLogDO::getSubType, criteria.getSubType());
        wrapper.eq(criteria.getBizId() != null, OperateLogDO::getBizId, criteria.getBizId());
        wrapper.eq(criteria.getSuccess() != null, OperateLogDO::getSuccess, criteria.getSuccess());
        
        // 模糊查询条件
        wrapper.like(!StrUtil.isEmpty(criteria.getContent()), OperateLogDO::getAction, criteria.getContent());
        wrapper.like(!StrUtil.isEmpty(criteria.getUserIp()), OperateLogDO::getUserIp, criteria.getUserIp());
        wrapper.like(!StrUtil.isEmpty(criteria.getUserAgent()), OperateLogDO::getUserAgent, criteria.getUserAgent());
        
        return wrapper;
    }

}
